/*
 * Copyright 2016 The Authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * Author: zhanglei_723@126.com
 */

#ifndef CARTOGRAPHER_SCAN_MATCHING_OCCUPIED_GRID_COST_FUNCTION_2D_H_
#define CARTOGRAPHER_SCAN_MATCHING_OCCUPIED_GRID_COST_FUNCTION_2D_H_

#include "mapping/grid_2d.h"
#include "sensor/point_cloud.h"
#include "ceres/ceres.h"

#include "scan_matching/nearest_search.h"

#include "mapping/probability_grid.h"
#include "mapping/probability_values.h"

#include "scan_matching/state.h"

namespace cartographer {
namespace scan_matching {

using namespace mapping;
// Creates a cost function for matching the 'point_cloud' to the 'grid' with
// a 'pose'. The cost increases with poorer correspondence of the grid and the
// point observation (e.g. points falling into less occupied space).
// ceres::CostFunction* CreateOccupiedGridCostFunction2D(
//     const double scaling_factor, const sensor::PointCloud& point_cloud, const transform::Rigid2d& initial_pose_estimate,
//     const Grid2D& grid);

class OccupiedGridCostFunction2D {
 public:
  OccupiedGridCostFunction2D(const double scaling_factor,
                              const sensor::PointCloud& point_cloud,
                              const transform::Rigid2d& initial_pose_estimate,
                              const Grid2D& grid) 
      : scaling_factor_(scaling_factor),
        point_cloud_(point_cloud),
        grid_(grid) {

      nearest_search_.BuildMapCSpaceByMaxProbability(point_cloud_, initial_pose_estimate, grid);
    }

    ~OccupiedGridCostFunction2D() {}
   
    bool ComputeResidualAndJacobianPoseGraph(const State& state, const Eigen::Matrix<double, 3, 1>& point, Eigen::Matrix<double, 1, 1> &residualXi, Eigen::Matrix<double, 1, 3> &jacobianXi);
    const sensor::PointCloud& GetPointCloud() {
        return point_cloud_;
    }
 private:
  OccupiedGridCostFunction2D(const OccupiedGridCostFunction2D&) = delete;
  OccupiedGridCostFunction2D& operator=(const OccupiedGridCostFunction2D&) =
      delete;

  const double scaling_factor_;
  const sensor::PointCloud& point_cloud_;
  const Grid2D& grid_;

  NearestSearch nearest_search_;
};

}  // namespace scan_matching
}  // namespace cartographer

#endif  // CARTOGRAPHER_SCAN_MATCHING_OCCUPIED_SPACE_COST_FUNCTION_2D_H_
